#!/bin/bash

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

[ -z "$DEST"] && DEST="$HOME/Synced/Picasaweb"

function backup_album
{
	album=$1
	DEST=$2

	echo "################### Processing album: $album"
	cnt=0

	IFS=$'\n'
	for photo in $(google picasa list "^$album$" | sed -e "s/,https.*//")
	do
		if [ -f "$DEST/$album/$photo" ]
		then
			#echo "Already downloaded: $photo"
			cnt=$(($cnt + 1))
		else
			mkdir -p "$DEST/$album"

			TMP=$(mktemp -d)

			echo -n "Getting: $photo... "
			query=$(echo "$photo" | sed -e "s/[^[:alnum:].]/./g")
			google picasa get --title "^$album$" --photo "^$query$" --dest "$TMP"
			# TODO: investigate cases when there are -1, -2, -3, -4, etc versions of files
			FILE=$(ls "$TMP/$album"/* | head -n1)
			mv "$FILE" "$DEST/$album/$photo"
			rm -rf "$TMP"
		fi
	done
	echo "Skipped: $cnt"
}

IFS=$'\n'
if [ -z "$1" ]
then
	for album in $(google picasa list-albums | sed -e "s/,https.*//" | grep -v "Eye-Fi")
	do
		backup_album "$album" "$DEST"
	done
else
	backup_album "$1" "$DEST"
fi
